<?php
namespace app\admin\controller\soft;
use app\admin\Adminbase;
use app\admin\model\SystemNav;


class PageCreate extends Adminbase 
{
    
    /**
    * admin/soft/Page_create/xmlGetList 
    * 需要登录 
    * @is_need_login false
    */
    public function xmlGetList(){
        $db = config('database.database');
        $tables = \Db::query("
            SELECT *,
                table_name table_names,
                table_comment comments,
                concat('systemSheet/',replace(table_name,'xw_','') ,'/index') url
            FROM information_schema.TABLES
            WHERE table_schema  = '$db'
            and  table_name not like '%xw_msg%'
            and  table_name not like '%xw_system%'
            and  table_name not like '%xw_wechat_menu%'
        ");
        $data["total"]= count($tables);
        $data["data"]= $tables;
        return $data;
    }
    
    /**
    * admin/soft/Page_create/xmlFieldInfo 
    * 需要登录 
    * @is_need_login false
    */
    public function xmlFieldInfo(){
        $param = request()->post();
        $keyWord = json_decode($param['keyWord'],true);
        
        $table_name = '';
        $column_name = '';
        foreach ($keyWord['filter'] as $key => $value) {
        	if($value['field']=="table_name"){
        	    $table_name = $value['value'];
        	}
            if($value['field']=="column_name"){
                $column_name = $value['value'];
            }
        }

        $result = db_multi_query("show full columns from $table_name where Field like '%$column_name%'"); 
        $data["total"]= count($result);
        $data["data"]= $result;
        return $data;
    }
    
    /**
    * 一键生成 
    * admin/soft/page_create/create 
    * 需要登录 
    * @is_need_login true
    */
    public function create($from='',$is_add_file='0'){
        //获取所有表信息
        $db = config('database.database');
        
        $sql = "
            SELECT 
                table_name table_names,
                table_comment comments,
                if(table_comment!='',table_comment,replace(table_name,'xw_','')) list_title,
                concat('systemSheet/',replace(table_name,'xw_','') ,'/index') url
            FROM information_schema.TABLES
            WHERE table_schema  = '$db' 
            and  table_name not like '%xw_msg%'
            and  table_name not like '%xw_system%'
            and  table_name not like '%xw_wechat_menu%'
        ";
        
        if($from)  $sql.= " and table_name  = '$from'";
        
        if(!$tables = \Db::query($sql)){
            $this->ReSucess();
        }
        
        //基础路径
        $file_path = base_path().'views/layout/filesCreate/';
        $save_path = base_path()."/views".( $from ? '/modules' : '/systemSheet' );
        
        //1、删除系统目录再生成
        if(!$from){
            $this->delDirAndFile($save_path,1);
            mkdir($save_path);
        }
        
        //导航数据操作
        $systemNav = new SystemNav;
        $systemNav->where('nav_status','-1')->delete();
        $systemNav->save([
            'sort'=>1,
            'nav_name'=>'系统目录',
            'nav_url'=>'',
            'nav_status'=>-1,
            'nav_pid'=>0,
        ]);
        $nav_pid = $systemNav->nav_id;
        $navData = [];
        
        //2、生成表目录和文件
        foreach ($tables as $keys => $value) {
            $dir = $save_path.'/'.str_replace("xw_","",$value['table_names']); 
            if(is_readable($dir.'/index.html'))  continue;
            
            mkdir($dir);
            
            //添加导航数据
            $navData[] = [
                'nav_name' => trim($value['list_title']),
                'nav_url' =>'systemSheet/'.str_replace("xw_","",$value['table_names']).'/index',
                'nav_status' => -1,
                'nav_pid' => $nav_pid,
            ];
            
            //生成html文件
            file_put_contents($dir.'/index.html',file_get_contents($file_path.'index.html'));
            file_put_contents($dir.'/edit.html',file_get_contents($file_path.'edit.html'));
            
            //生成xml文件
            $xmlStr = file_get_contents($file_path.'config.xml');
            $fullColumns = \Db::query("show full columns from ".$value['table_names']); 
            $value['search_fields'] = join(",",array_column($fullColumns, 'Field'));
            $value['cells'] = '';
            $value['rows']='';
            $value['table_key'] = 'id';
            foreach ($fullColumns as $key => $val) {
                $field = $val['Field'];
                //标题
                $title = explode(' ', $val['Comment']);
                $title = $title[1] ? $title : explode('；', $val['Comment']);
                $title = $title[1] ? $title : explode('：', $val['Comment']);
                $title = $title[1] ? $title : explode('|', $val['Comment']);
                $title = $title[1] ? $title : explode(' : ', $val['Comment']);
                $title = $title[1] ? $title : explode(':', $val['Comment']);
                $title = $title[1] ? $title : explode('（', $val['Comment']);
                $title = $title[1] ? $title : explode('(', $val['Comment']);
                $title = $title[1] ? $title : explode('，', $val['Comment']);
                $title = $title[1] ? $title : explode(' , ', $val['Comment']);
                $title = $title[1] ? $title : explode(',', $val['Comment']);
                $title = $title[0] ?: $field;
                //属性
                $type = 'text';  
                $align = 'left'; 
                $width = $key == 0 ? '60': '100';
                if( strstr($val['Type'],"decimal")  || strstr($val['Type'],"float") || strstr($val['Type'],"bigint") || strstr($val['Type'],"mediumint") || strstr($val['Type'],"smallint")){
                    $type = 'number';
                }else if(strstr($val['Type'],"timestamp")){
                    $type = 'datetime';
                    $align = 'center';
                }
                if( count($fullColumns) == $key+1){
                    $width = ''; 
                }
                //添加grid列
                $value['cells'] .= "
                <cell type='$type' title='$title' field='$field' align='$align' minWidth='100' width='$width'/>";
                
                //查主键
                if($val['Extra'] == 'auto_increment'){
                    $value['table_key'] = $field;
                }else{
                    //添加form列
                    $value['rows'] .= "
                    <row  type='$type'  title='$title' field='$field'  value='' colspan='1' edit='true'/>";
                }
            }
            foreach ($value as $key => $val) { $xmlStr = str_replace("{{{$key}}}",$val,$xmlStr); }
            file_put_contents($dir.'/config.xml',$xmlStr);
        }
        
        //添加导航数据
        model('SystemNav')->saveAll($navData);
            
        //返回
        $this->ReSucess();
    }
    
    
    /**
     * 删除目录及目录下所有文件或删除指定文件
     * @param str $path 待删除目录路径
     * @param int $delDir 是否删除目录，1或true删除目录，0或false则只删除文件保留目录
     * @return bool 返回删除状态
     */
    private function delDirAndFile($path, $delDir = false) {
        if (is_array($path)) {
            foreach ($path as $subPath) {
                $this->delDirAndFile($subPath, $delDir);
            }
        }
        if (is_dir($path)) {
            $handle = opendir($path);
            if ($handle) {
                while (false !== ($item = readdir($handle))) {
                    if ($item != "." && $item != "..") {
                        is_dir("$path/$item") ? 
                        $this->delDirAndFile("$path/$item", $delDir) : 
                        unlink("$path/$item");
                    }
                }
                closedir($handle);
                if ($delDir) { return rmdir($path);  }
            }
        } else {
            if (file_exists($path)) {
                return unlink($path);
            } else {
                return false;
            }
        }
    }

}
    